using UnityEngine;
using System.Collections;

public class ArcherAI : MonoBehaviour {

    public GameObject projectile;
    private GameObject[] obs;
    private Vector3 moveDirection;
    
    private float timeLastFired = 10.0f;
    public float attackCooldown = 1.0f;
    
    // Use this for initialization
    void Start()
    {
        obs = GameObject.FindGameObjectsWithTag("Player");
    }
    
    // Update is called once per frame
    void Update()
    {
        if(Network.isServer){
            GameObject closest = FindClosestEnemy(gameObject);
            transform.LookAt(closest.transform);
            
            Vector3 diff = closest.transform.position - transform.position;
            float curDistance = diff.sqrMagnitude;
            curDistance =  Mathf.Sqrt(curDistance);
            
            // if we're really far away don't do anything
            if (curDistance > 300)
                return;
            
            //else attack
            if (timeLastFired <= Time.time)
            {
                moveDirection = transform.TransformDirection(Vector3.forward);
                moveDirection.Normalize();
                moveDirection = Vector3.Scale(moveDirection,new Vector3(18,18,18));
                GameObject spawn = Network.Instantiate(projectile, this.transform.position + moveDirection, this.transform.rotation, 0) as GameObject;
                timeLastFired = Time.time + attackCooldown;
            }
            networkView.RPC("UpdateEnemyPosition",RPCMode.Server,transform.position,transform.rotation);
        }
    }
    
    // Find the closest enemy (I mean player)
    public static GameObject FindClosestEnemy(GameObject controlled)
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Player");
        GameObject closest = null;
        float distance = Mathf.Infinity;
        Vector3 position = controlled.transform.position;
        foreach (GameObject go in gos)
        {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            curDistance =  Mathf.Sqrt(curDistance);
            if (curDistance < distance)
            {
                closest = go;
                distance = curDistance;
            }
        }
    return closest;
    
    }
    [RPC]
    void UpdateEnemyPosition(Vector3 pos, Quaternion rot){
        transform.position = pos;
        transform.rotation = rot;
    }
}